import * as THREE from "three";
import { ref, watchEffect, onUnmounted } from "vue";
let cameraPosition = ref(1.5);

//场景
const scene = new THREE.Scene();
//相机
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);

// 创建渲染器对象
const renderer = new THREE.WebGLRenderer(); //渲染器

//立方体
export function lifangti() {
  //设置画布尺寸
  const width = 1000; //宽度
  const height = 600; //高度
  renderer.setSize(width, height);
  renderer.setClearColor('#B0E0E6')
  document.getElementById("webgl").appendChild(renderer.domElement);
  //控制器
  var geometry = new THREE.BoxGeometry(1, 1, 1);
  var material = new THREE.MeshBasicMaterial({ color: 0x87CEFA });
  var cube = new THREE.Mesh(geometry, material);
  scene.add(cube);
  camera.position.z = cameraPosition.value;
  watchEffect(() => {
    camera.position.z = cameraPosition.value;
  });
  //组件销毁要清除模型实例

  onUnmounted(() => {
    scene.clear();
    renderer.dispose();
    // renderer.forceContextLoss();
    // renderer.content = null;
  });

  const animate =  ()=> {
    requestAnimationFrame(animate);
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render(scene, camera);
  };

  animate();
}
//更改参数
let flag = ref(1);
export function change(direction) {
  if (cameraPosition.value == 1.5) {
    flag.value = 1;
  } else if (cameraPosition.value == 10.5) {
    flag.value = 0;
  }
  if (flag.value == 1) {
    cameraPosition.value++;
  } else if (flag.value == 0) {
    cameraPosition.value--;
  }
}
export function ren() {
  // 定义threejs输出画布的尺寸(单位:像素px)
  const width = 800; //宽度
  const height = 500; //高度
  renderer.setSize(width, height); //设置three.js渲染区域的尺寸(像素px)
  renderer.render(scene, camera); //执行渲染操作
  document.body.appendChild(renderer.domElement);

  document.getElementById("webgl").appendChild(renderer.domElement);
}
